package com.ultrapower.ctool.xn_app;

import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.ultrapower.ctool.ConfUtils;
import com.ultrapower.ctool.bean.UserVo;
import com.ultrapower.ctool.core.CustomApplication;
import com.ultrapower.ctool.http.BaseActivity;
import com.ultrapower.ctool.model.RegisterRolePirVO;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class RegisterActivity extends BaseActivity {
    private int FLAG = 0;
    private EditText username;

    private EditText password;
    private RegisterActivity registerActivity = this;
    private TextView userRoleText;
    private TextView dtypeText;
    private TextView nicknameText;
    private Button registerButton;
    //private OkHttpClient client = new OkHttpClient();
    private Gson gson = new Gson();
    private AutoCompleteTextView district;
    private CustomApplication application;
    //private AutoCompleteAdater cursorAdapter;
    //private ArrayAdapter<Map> areadapter;
    private Spinner userroleSpinner;
    private Spinner dtypeSpinner;
    public List<UserVo> suggest;
    public ArrayAdapter<UserVo> aAdapter;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    Toast.makeText(getApplicationContext(), "用户名添加成功", Toast.LENGTH_SHORT).show();
                    //district.
                    finish();
                    break;
                case 0:
                    Toast.makeText(getApplicationContext(), "系统出现异常", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        district = ((AutoCompleteTextView) this.findViewById(R.id.district));
        username = (EditText) findViewById(R.id.login_id);
        password = (EditText) findViewById(R.id.login_pwd);
        userroleSpinner = (Spinner) findViewById(R.id.user_role);
        dtypeSpinner = (Spinner) findViewById(R.id.dtype);
        userRoleText = (TextView) findViewById(R.id.user_role_text);
        dtypeText = (TextView) findViewById(R.id.dtypeText);
        nicknameText = (TextView) findViewById(R.id.nickname);
        registerButton = (Button) findViewById(R.id.registerButton);
        application = (CustomApplication) getApplication();
        //cursorAdapter = new AutoCompleteAdater(this, R.layout.simple_dropdown_item_1line, null, "cn", android.R.id.text1);
        ///district.setThreshold(1);
        ///district.setAdapter(cursorAdapter);
        //System.out.println(android.R.id.text1);
        suggest = new ArrayList<UserVo>();
        district.addTextChangedListener(new TextWatcher() {

            public void afterTextChanged(Editable editable) {

            }

            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String newText = s.toString();
                new RegisterActivity.getJson().execute(newText);
            }

        });

        initData();
        registerButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final String districtValue = district.getText().toString();
                final String userName = username.getText().toString().trim();    //获取当前输入的用户名和密码信息
                final String userPwd = password.getText().toString().trim();
                final String nickname = nicknameText.getText().toString().trim();

                String roleId = ((RegisterRolePirVO) userroleSpinner.getSelectedItem()).getId();
                final String userCheck = roleId.split(".").length == 0 ? roleId : roleId.split(".")[0];
                //final String _id = suggest.get(0).getId();
                if (userName.equals("")) {
                    Toast.makeText(getApplicationContext(), "登录帐号不能为空", Toast.LENGTH_SHORT).show();
                } else if (userPwd.equals("") || "".equals(userPwd)) {
                    Toast.makeText(getApplicationContext(), "密码不能为空", Toast.LENGTH_SHORT).show();
                } else if (userCheck.equals("") || "".equals(userCheck)) {
                    Toast.makeText(getApplicationContext(), " 角色不能为空", Toast.LENGTH_SHORT).show();
                } else if (nicknameText.equals("") || "".equals(nicknameText)) {
                    Toast.makeText(getApplicationContext(), " 用户名不能为空", Toast.LENGTH_SHORT).show();
                } else if (suggest.size()<1) {
                    Toast.makeText(getApplicationContext(), " 所属行政区格式错误", Toast.LENGTH_SHORT).show();
                } else {
                    //访问后台
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                OkHttpClient client = new OkHttpClient();
                                RequestBody requestBody = new FormBody.Builder()
                                        .add("login_id", userName)
                                        .add("login_pwd", userPwd)
                                        .add("rid", ((RegisterRolePirVO) userroleSpinner.getSelectedItem()).getId())
                                        .add("dtype", ((RegisterRolePirVO) dtypeSpinner.getSelectedItem()).getId())
                                        .add("xid", suggest.get(0).getXid())
                                        .add("nickname", nickname)
                                        .add("userId", String.valueOf(application.getLoginUser().getLogin_id()))
                                        .build();
                                Request request = new Request.Builder().url(ConfUtils.SERVICE_URL + "form/doAdd/c_pt_user").post(requestBody).build();
                                Response response = client.newCall(request).execute();
                                if (response.isSuccessful()) {//成功
                                    String result = response.body().string();
                                    Map<String, Object> resultMap = gson.fromJson(result, Map.class);
                                    System.out.println(resultMap);
                                    if ((boolean) resultMap.get("success")) {

                                        Message message = new Message();
                                        message.what = 1;
                                        handler.sendMessage(message);


                                    } else {
                                        Message message = new Message();
                                        message.what = 0;
                                        handler.sendMessage(message);
                                    }
                                }
                            } catch (Exception e) {
                                Message message = new Message();
                                message.what = 0;
                                handler.sendMessage(message);
                                e.printStackTrace();
                            }
                        }
                    }).start();
                }
            }
        });



    }

    public void initData() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient client = new OkHttpClient();
                    //获得角色列表
                    Request request = new Request.Builder().url(ConfUtils.SERVICE_URL + "widget/comboJson/c_pt_user-rid?userId=" + String.valueOf(application.getLoginUser().getLogin_id())).build();
                    Response response = client.newCall(request).execute();
                    if (response.isSuccessful()) {//成功
                        String result = response.body().string();
                        final List<RegisterRolePirVO> roles = gson.fromJson(result, new TypeToken<List<RegisterRolePirVO>>() {
                        }.getType());
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                ArrayAdapter<RegisterRolePirVO> aradapter = new ArrayAdapter<RegisterRolePirVO>(getApplicationContext(), android.R.layout.simple_spinner_item, roles);
                                aradapter.setDropDownViewResource(R.layout.simple_dropdown_item_1line);
                                userroleSpinner.setAdapter(aradapter);
                                userroleSpinner.setOnItemSelectedListener(
                                        new AdapterView.OnItemSelectedListener() {
                                            public void onItemSelected(
                                                    AdapterView parent, View view, int position, long id) {
                                                RegisterRolePirVO item = (RegisterRolePirVO) userroleSpinner.getSelectedItem();
                                                userRoleText.setText((String) item.getCn());
                                            }

                                            public void onNothingSelected(AdapterView parent) {
                                            }
                                        });
                            }
                        });
                    }
                    //获得部门类型列表
                    Request dtypeRequest = new Request.Builder().url(ConfUtils.SERVICE_URL + "widget/comboJson/c_pt_user-dtype?userId=" + String.valueOf(application.getLoginUser().getLogin_id())).build();
                    Response dtypeResponse = client.newCall(dtypeRequest).execute();
                    if (dtypeResponse.isSuccessful()) {//成功
                        String result = dtypeResponse.body().string();
                        final List<RegisterRolePirVO> dtypes = gson.fromJson(result, new TypeToken<List<RegisterRolePirVO>>() {
                        }.getType());
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                ArrayAdapter<RegisterRolePirVO> dypeAradapter = new ArrayAdapter<RegisterRolePirVO>(getApplicationContext(), R.layout.simple_dropdown_item_1line, dtypes);
                                dypeAradapter.setDropDownViewResource(R.layout.simple_dropdown_item_1line);
                                dtypeSpinner.setAdapter(dypeAradapter);
                                dtypeSpinner.setOnItemSelectedListener(
                                        new AdapterView.OnItemSelectedListener() {
                                            public void onItemSelected(
                                                    AdapterView parent, View view, int position, long id) {
                                                RegisterRolePirVO item = (RegisterRolePirVO) dtypeSpinner.getSelectedItem();
                                                dtypeText.setText((String) item.getCn());
                                            }

                                            public void onNothingSelected(AdapterView parent) {
                                            }
                                        });
                            }
                        });
                    }
                } catch (Exception e) {
                    Message message = new Message();
                    message.what = 0;
                    handler.sendMessage(message);
                    e.printStackTrace();
                }
            }
        }).start();
    }

    class getJson extends AsyncTask<String, String, String> {
        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            aAdapter = new ArrayAdapter<UserVo>(getApplicationContext(), R.layout.simple_dropdown_item_1line, suggest);
            district.setThreshold(1);
            district.setAdapter(aAdapter);
            aAdapter.notifyDataSetChanged();
        }

        @Override
        protected String doInBackground(String... key) {
            suggest.clear();
            Response response = null;
            if (key.length != 0 && !"".equals(key[0])) {
                try {
                    OkHttpClient client = new OkHttpClient();
                    RequestBody requestBody = new FormBody.Builder()
                            .add("field", "xid")
                            .add("code", "c_pt_user")
                            .add("userId", String.valueOf(application.getLoginUser().getLogin_id()))
                            .add("like", key.length == 0 ? "" : key[0])
                            .build();
                    Request request = new Request.Builder().url(ConfUtils.SERVICE_URL + "widget/findLikeJson").post(requestBody).build();
                    response = client.newCall(request).execute();
                    if (response.isSuccessful()) {//成功
                        String result = response.body().string();
                        System.out.println(result);
                        suggest = gson.fromJson(result, new TypeToken<List<UserVo>>() {
                        }.getType());
                        System.out.println(suggest);
                    }
                } catch (Exception e) {
                    Log.w("Error", e.getMessage());
                }
            }
            return null;
        }

    }


}